package com.ihr360.cnb.module.insurance.controller;

import com.alibaba.fastjson.JSONObject;
import com.ihr360.cnb.module.insurance.model.StaffDataAuthorityCodeConstants;
import com.ihr360.cnb.module.insurance.service.MonthlyLedgerAggregateService;
import com.ihr360.cnb.module.insurance.service.StaffIdCheckService;
import com.ihr360.cnb.module.insurance.service.feign.InsuranceMonthlyLedgerService;
import com.ihr360.commons.vo.PageData;
import com.ihr360.insurance.entity.request.MonthlyLedgerRequest;
import com.ihr360.insurance.entity.request.StaffLedgerRequest;
import com.ihr360.insurance.entity.response.LedgerResponse;
import com.ihr360.insurance.entity.vo.StaffBenefitVo;
import com.ihr360.maven.plugin.ModuleCodeStore;
import com.ihr360.maven.plugin.annotation.FunctionDefinition;
import com.ihr360.maven.plugin.annotation.ModuleDefinition;
import com.ihr360.shared.advice.response.DisableResponseAdvice;
import com.ihr360.validation.ValidationUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author Stone.Shi
 * @description
 * @date 2018-05-23 19:55:27.
 */
@RestController
@RequestMapping("/monthlyLedgers")
@ModuleDefinition(mainModuleCode = ModuleCodeStore.Module.BENEFIT_CODE,
        mainModuleName = ModuleCodeStore.Module.BENEFIT_NAME,
        subModuleCode = ModuleCodeStore.Module.Benefit.STANDING_BOOK_CODE,
        subModuleName = ModuleCodeStore.Module.Benefit.STANDING_BOOK_NAME)
public class MonthlyLedgerAggregateController {

    @Autowired
    private StaffIdCheckService staffIdCheckService;

    @Autowired
    private InsuranceMonthlyLedgerService insuranceMonthlyLedgerService;

    @Autowired
    private MonthlyLedgerAggregateService monthlyLedgerAggregateService;

    @FunctionDefinition(functionName = "获取可添加到社保公积金台账中的员工列表", functionCode = ModuleCodeStore.Function.VIEW)
    @RequestMapping(value = "/dosearch", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_VALUE)
    public PageData<StaffBenefitVo> search(@RequestParam String companyId,
                                           @RequestParam String userId,
                                           @RequestBody StaffLedgerRequest req) {
        return monthlyLedgerAggregateService.getCanAddToLedgerStaffs(companyId, userId, req, StaffDataAuthorityCodeConstants.ARCHIVE_AUTHORITY_CODE_VIEW);
    }

    @FunctionDefinition(functionName = "将选择的员工添加到台账", functionCode = ModuleCodeStore.Function.ADD)
    @RequestMapping(value = "/add", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_VALUE)
    @DisableResponseAdvice
    public LedgerResponse addLedgerStaff(@RequestParam String companyId,
                                         @RequestParam String userId,
                                         @RequestBody List<StaffBenefitVo> staffBenefits,
                                         @RequestParam Integer ledgerYear,
                                         @RequestParam Integer ledgerMonth) {
        ValidationUtils.rejectIfEmpty(staffBenefits, null, "要保存的数据不能为空");
        staffIdCheckService.check(staffBenefits.stream().map(vo -> vo.getStaff().getId()).collect(Collectors.toList()));
        return insuranceMonthlyLedgerService.addLedgerStaff(companyId, userId, staffBenefits, ledgerYear, ledgerMonth);
    }

    @FunctionDefinition(functionName = "将全部员工添加到台账", functionCode = ModuleCodeStore.Function.ADD)
    @RequestMapping(value = "/addAll", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_VALUE)
    public LedgerResponse addAllLedgerStaff(@RequestParam String companyId,
                                            @RequestParam String userId,
                                            @RequestParam Integer ledgerYear,
                                            @RequestParam Integer ledgerMonth) {
        return monthlyLedgerAggregateService.addAllLedgerStaff(companyId, userId, ledgerYear, ledgerMonth, StaffDataAuthorityCodeConstants.ARCHIVE_AUTHORITY_CODE_VIEW);
    }

    @FunctionDefinition(functionName = "导出台账数据", functionCode = ModuleCodeStore.Function.EXPORT)
    @RequestMapping(value = "/export", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
    public void exportExcel(@RequestParam String companyId,
                            @RequestParam String userId,
                            @RequestParam String reqString,
                            HttpServletResponse response) throws IOException {
        MonthlyLedgerRequest req = new MonthlyLedgerRequest();
        try {
            req = JSONObject.parseObject(reqString, MonthlyLedgerRequest.class);
        } catch (Exception e) {
            ValidationUtils.reject("", "下载参数错误");
        }
        StringBuilder fileNameBuilder = new StringBuilder();
        fileNameBuilder
                .append(req.getLedgerYear())
                .append("年")
                .append(req.getLedgerMonth())
                .append("月").append("社保公积金台账.xls");
        response.setHeader("x-filename", URLEncoder.encode(fileNameBuilder.toString(), "UTF-8"));
        monthlyLedgerAggregateService.exportExcel(companyId, userId, reqString, response.getOutputStream());
    }

}
